package com.hy.study;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseConfigurer;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;

/**
 * 根据不同的环境初始化不同的bean 激活方式 1 通过jvm参数来切换  -Dspring.profiles.active=test|dev|prod 激活方式 2 通过代码方式来激活
 *
 * @author huyong
 * @date 2024 年 01 月 03 日 10:58: 11
 */
@Configuration
@PropertySource(encoding = "UTF-8", value = {"classpath:jdbc.properties"})
public class JdbcConfig implements EmbeddedValueResolverAware {

    @Value("${jdbc.username}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;
    private String driverClass;
    private String url;

    @Override
    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
        this.driverClass = stringValueResolver.resolveStringValue("${jdbc.driverClass}");
        this.url = stringValueResolver.resolveStringValue("${jdbc.url}");

    }

    // 根据不同的参数初始化不同的dataSource

    @Profile(value = "test")
    @Bean(name = "dataSource")
    public DataSource testDS() {
        return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).addScript("classpath:com.hy.study.jdbc/sql/schema.sql").addScript("classpath:com.hy.study.jdbc/sql/test-data.sql").build();
    }

    @Bean(name = "dataSource")
    @Profile(value = "dev")
    public DataSource devDS() {
        return builderDataSource(new DruidDataSource());
    }


    public DataSource builderDataSource(DruidDataSource dataSource) {
        dataSource.setUsername(this.userName);
        dataSource.setPassword(this.password);
        dataSource.setDriverClassName(this.driverClass);
        dataSource.setUrl(this.url);
        return dataSource;
    }
}
